package com.x.mvp.crypto;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public final class GZipUtil {

    public static byte[] compress(byte[] source) throws IOException {
        byte[] result = source;
        if (source != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(out);
            gzip.write(source);
            gzip.finish();
            result = out.toByteArray();
            out.close();
            gzip.close();
        }
        return result;
    }

    public static byte[] decompress(byte[] source) throws IOException {
        byte[] result = source;
        if (source != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayInputStream in = new ByteArrayInputStream(source);
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            result = out.toByteArray();
            out.close();
            gunzip.close();
            in.close();
        }
        return result;
    }
}
